package name.vaccari.matteo.tai.phonedirectory.web;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import name.vaccari.matteo.tai.phonedirectory.model.PeopleRepository;
import name.vaccari.matteo.tai.phonedirectory.model.Person;
import name.vaccari.matteo.tai.phonedirectory.network.Servlet;

public class PeopleServlet implements Servlet {

	public final PeopleRepository repository;

	public PeopleServlet(PeopleRepository repository) {
		this.repository = repository;
	}

	public String doGet(String path) {
		if ("/new".equals(path)) {
			Map<String, Object> model = new HashMap<String, Object>(); 
			return processTemplate("new-person.ftl", model);
		} 
		Map<String, Object> model = 
			createModelMapWith("people", repository.getPeople(0, 10));
		return processTemplate("list-people.ftl", model);
	}

	private Map<String, Object> createModelMapWith(String key,
			List<Person> value) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put(key, value);
		return model;
	}

	private String processTemplate(String name, Map<String, Object> model) {
		Template template = getTemplate(name);
		Writer out = new StringWriter();
		try {
			template.process(model, out );
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return out.toString();
	}

	private Template getTemplate(String name) {
		try {
			Configuration configuration = new Configuration();
			configuration.setDirectoryForTemplateLoading(new File("./templates"));
			return configuration.getTemplate(name);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public String convertPersonToTableRow(Person person) {
		return "<tr><td>" + person.getLastName() +
				"</td><td>" + person.getFirstName() +
				"</td><td>" + person.getMobile() +
				"</td></tr>";
	}

	public String doPost(String path, Map<String, String> params) {
		Person person = new Person();
		person.setFirstName(params.get("firstName"));
		repository.add(person);
		return "/list";
	}

}
